<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库名称">
              <j-search-select-tag type="list" v-model="queryParam.warehouse" dict="hz_wms_warehouse_info,name,id,wms,status='Y'" placeholder="请选择可用仓库" />  
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="分区名称">
              <a-input placeholder="请输入分区名称或代码" v-model="queryParam.partitionName"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="8" :lg="7" :md="8" :sm="24">
              <a-form-item label="货架查询">
                <a-input placeholder="请输入货架代码进行模糊查询" v-model="queryParam.shelvesCode"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button
        @click="handlePriority('remove')"
        type="danger"
        size="small"
        :loading="removeLoading"
        :disabled="removeLoading"
        >移除优先级</a-button
      >
      <a-button
        @click="handlePriority('auto')"
        type="primary"
        size="small"
        :loading="autoLoading"
        :disabled="autoLoading"
        >自动优先级</a-button
      >
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData"
      >
        <template slot="priorityLevelSlot" slot-scope="text, record, index">
          <!-- 优先级输入框 -->
          <a-input-number
            v-model="record.priorityLevel"
            :min="1"
            :max="ipagination.total"
            :precision="0"
            :formatter="transformNum"
            :parser="transformNum"
            @change="(value) => priorityLevelChange(value, record, index)"
            style="width: 100%"
          ></a-input-number>
        </template>
      </a-table>
    </div>
    <a-modal
      :visible="progressVisible"
      :closable="false"
      :maskClosable="false"
      :width="500"
      @ok="progressFinish"
      :footer="null"
    >
      <div class="progress">
        <div>{{ percentModel.percent < 100 ? '正在调整' : '调整优先级成功' }}</div>
        <a-progress :percent="percentModel.percent" />
        <div v-if="percentModel.percent < 100">正在调整优先级，大约剩余{{ percentModel.countdown }}s</div>
      </div>
      <div style="text-align: right" v-if="percentModel.percent === 100">
        <a-button key="submit" type="primary" @click="progressFinish">确定</a-button>
      </div>
    </a-modal>
    <!-- <shelves-location-print ref="printRef"></shelves-location-print> -->
  </a-card>
</template>

<script>
import Vue from 'vue'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { postFormAction, getAction, postAction } from '@api/manage'
// import shelvesLocationPrint from './shelvesLocationPrint.vue'
import { ACCESS_TOKEN, USER_INFO } from "@/store/mutation-types"
import { EventBus } from './eventBus'
export default {
  name: 'ShelvesLocationAdjustList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {},
  data() {
    return {
      description: '仓库货架库位管理页面',
      disableMixinCreated: true, //手动调用 LoadData
      removeLoading: false, //移除优先级
      autoLoading: false, //自动优先级
      progressVisible: false,
      percentModel: {
        percent:0, //进度
        countdown: '', //倒计时
      },
      socket:'',
      // 表头
      columns: [
        {
          title: 'NO',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库名称',
          align: 'center',
          dataIndex: 'warehouseId_dictText',
        },
        {
          title: '分区名称',
          align: 'center',
          dataIndex: 'partitionName',
        },
        {
          title: '分区代码',
          align: 'center',
          dataIndex: 'partitionCode',
        },
        {
          title: '库位代码',
          align: 'center',
          dataIndex: 'locationCode',
        },
        {
          width: 180,
          title: '库位优先级',
          align: 'center',
          dataIndex: 'priorityLevel',
          scopedSlots: { customRender: 'priorityLevelSlot' },
        },
      ],
      url: {
        list: '/wms/shelves/shelvesLocation/list',
        delete: '/wms/shelves/shelvesLocation/delete',
        deleteBatch: '/wms/shelves/shelvesLocation/deleteBatch',
        exportXlsUrl: '/wms/shelves/shelvesLocation/exportXls',
        importExcelUrl: 'shelves/shelvesLocation/importExcel',
        removePriority: '/wms/shelves/shelvesLocation/removePriority',
        autoPriority: '/wms/shelves/shelvesLocation/autoPriority',
        adjustPriority: '/wms/shelves/shelvesLocation/adjustPriority',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  mounted(){
    EventBus.$on('websocket-onopen2', this.handleOpen)
    EventBus.$on('websocket-message2', this.handleMessage)
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    selectRowData(record, index) {
      const that = this
      return {
        on: {
          dblclick: () => {
            this.handleDetail(record)
          },
        },
      }
    },
    //编辑优先级
    priorityLevelChange(value, record, index) {
      if (value) {
        this.$set(this.dataSource[index], 'priorityLevel', value)
      }
    },
    //优先级输入框  只能输入整数
    transformNum(value) {
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/\./g, '') : 1
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/\./g, '') : 1
      } else {
        return 1
      }
    },
    //移除优先级
    handlePriority(type) {
      const that = this
      this.$confirm({
        title: `确定要进行批量${type === 'remove' ? '移除' : '自动'}优先级吗？`,
        onOk() {
          let params = that.getQueryParams() //查询条件
          //移除
          if (type === 'remove') {
            that.removeLoading = true
            getAction(that.url.removePriority, params)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.removeLoading = false
              })
          } else {
            //自动调整优先级
            //打开连接
            that.handleOpen()
            //接收消息
            that.handleMessage()
          }
        },
      })
    },
    //建立webscoket
    // createWS() {
    //   const that = this
    //   that.autoLoading = true
    //   let userId = Vue.ls.get(USER_INFO).id
    //   let url =window._CONFIG['socketURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId + '_autoPriority'  
    //   that.socket = new WebSocket(url)
    //   that.socket.onopen = () => {
    //     that.sendParams()
    //   }
    //   that.socket.onmessage = (event) => {
    //     if (event.data) {
    //       const data = JSON.parse(event.data)
    //       that.percentModel = {
    //         percent: data.msgTxt && data.msgTxt.progress ? Number((Number(data.msgTxt.progress) * 100).toFixed()) : 0,
    //         countdown: data.msgTxt && data.msgTxt.countdown ? data.msgTxt.countdown : '0',
    //       }
    //       that.progressVisible = true
    //       if (that.percentModel.percent === 100) {
    //         that.autoLoading = false
    //       }
    //     }
    //   }
    // },
    handleOpen() {
      this.autoLoading = true
      let params = this.getQueryParams() //查询条件
      getAction(this.url.autoPriority, params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            //this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.autoLoading = false
        })
    },
    //webscoke 返回消息
    handleMessage(data) {
      if(data && data.msgTxt){
      this.percentModel = {
        percent: data.msgTxt && data.msgTxt.progress ? Number((Number(data.msgTxt.progress) * 100).toFixed()) : 0,
        countdown: data.msgTxt && data.msgTxt.countdown ? data.msgTxt.countdown : '0',
      }
      this.progressVisible = true
      if (this.percentModel.percent === 100) {
        this.confirmLoading = false
        this.$emit('loadingBack', false)
      }
    }
    },
    //自动调整优先级
    // sendParams() {
    //   this.autoLoading = true
    //   let params = this.getQueryParams() 
    //   getAction(this.url.autoPriority, params)
    //     .then((res) => {
    //       if (res.success) {
    //         this.$message.success(res.message)
    //         this.$emit('ok')
    //       } else {
    //         this.$message.warning(res.message)
    //       }
    //     })
    //     .finally(() => {
    //       this.autoLoading = false
    //     })
    // },
    //确定  调整优先级
    submitForm() {
      const locations = this.dataSource.map((item) => {
        return { id: item.id, priorityLevel: item.priorityLevel }
      })
      postAction(this.url.adjustPriority, locations).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //进度完成
    progressFinish() {
      this.progressVisible = false
      this.$emit('ok')
      // this.closeConnection()
      EventBus.$off('websocket-onopen2', this.handleOpen)
      EventBus.$off('websocket-message2', this.handleMessage)
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'partitionId', text: '分区', dictCode: '' })
      fieldList.push({ type: 'string', value: 'code', text: '库位代码', dictCode: '' })
      fieldList.push({ type: 'int', value: 'priorityLevel', text: '优先级', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '库位状态', dictCode: 'is_enable' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
.ant-card-body .table-operator {
  text-align: right;
}
/deep/
  .ant-table-middle
  > .ant-table-content
  > .ant-table-scroll
  > .ant-table-body
  > table
  > .ant-table-tbody
  > tr
  > td {
  padding: 8px;
}
.progress {
  div:nth-child(1) {
    font-size: 15px;
  }
  /deep/.ant-progress {
    margin: 20px 0 10px 0;
  }
}
</style>
